﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WeSSysUser.model;
using System.ServiceModel.Channels;
using System.Configuration;
using System.Data;
using WeSSysUser.controller;
using WeSSysUser.util;

namespace WeSSysUser
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class WeSSysUser : IWeSSysUser
    {
        public ActivateAccountResult activateAccount(int id, string token)
        {
            SysUserResultStatus request = requestIP();
            if (request.statusCode == 0)
            {
                try
                {
                    DataTable dt = SysUserController.getUserById(id);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        DateTime datetimeNow = DateTime.Now;
                        DateTime datetimeRegister = Common.strToDateTime(dt.Rows[0]["RegisteredDate"].ToString());
                        if ((datetimeNow - datetimeRegister).TotalHours > int.Parse(ConfigurationManager.AppSettings["User_ActivateTimeSpan_InHours"].ToString()))
                            return new ActivateAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = ActivateAccountResult.STATUS_EXPIRED_TIME_CODE,
                                    statusText = ActivateAccountResult.STATUS_EXPIRED_TIME_TEXT
                                }
                            };

                        if (token != dt.Rows[0]["ActivatedToken"].ToString())
                            return new ActivateAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = ActivateAccountResult.STATUS_INVALID_TOKEN_CODE,
                                    statusText = ActivateAccountResult.STATUS_INVALID_TOKEN_TEXT
                                }
                            };

                        if (dt.Rows[0]["ActivatedDate"] != null && dt.Rows[0]["ActivatedDate"].ToString() != "")
                            return new ActivateAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = ActivateAccountResult.STATUS_ALREADY_ACTIVATED_CODE,
                                    statusText = ActivateAccountResult.STATUS_ALREADY_ACTIVATED_TEXT
                                }
                            };

                        string avatar = ((id % 11) + 1) + ".png";
                        object[,] parameters = { { "@Id", id },
                                                 { "@ActivatedDate", datetimeNow.ToString("yyyyMMddHHmmss") },
                                                 { "@RoleId", "1"},
                                                 { "@Avatar", avatar}};
                        bool result = DB.exec("update SysUser set ActivatedDate = @ActivatedDate, RoleId = @RoleId, avatar = @avatar where Id = @Id;", parameters);
                        if (result)
                        {
                            return new ActivateAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = ActivateAccountResult.STATUS_VALID_TOKEN_CODE,
                                    statusText = ActivateAccountResult.STATUS_VALID_TOKEN_TEXT
                                }
                            };
                        }
                        else
                            return new ActivateAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = ActivateAccountResult.STATUS_GENERAL_ERROR_CODE,
                                    statusText = ActivateAccountResult.STATUS_GENERAL_ERROR_TEXT
                                }
                            };
                    }
                    else
                    {
                        return new ActivateAccountResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = ActivateAccountResult.STATUS_INVALID_USER_CODE,
                                statusText = ActivateAccountResult.STATUS_INVALID_USER_TEXT
                            }
                        };
                    }
                }
                catch (Exception ex)
                {
                    return new ActivateAccountResult
                    {
                        sysUserResultStatus = 
                        {
                            statusCode = 500,
                            statusText = ex.Message
                        }
                    };
                }
            }
            else
            {

                return new ActivateAccountResult
                {
                    sysUserResultStatus = request
                };
            }
        }

        public CheckAccountResult checkAccount(int id)
        {
            SysUserResultStatus request = requestIP();
            if (request.statusCode == 0)
            {
                try
                {
                    DataTable dt = SysUserController.getUserById(id);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["STATUS"].ToString() != "0")
                            return new CheckAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = CheckAccountResult.STATUS_BANNED_CODE,
                                    statusText = CheckAccountResult.STATUS_BANNED_TEXT
                                }
                            };
                        else
                            return new CheckAccountResult
                            {
                                sysUserResultStatus = new SysUserResultStatus
                                {
                                    statusCode = CheckAccountResult.STATUS_UNAVAILABLE_CODE,
                                    statusText = CheckAccountResult.STATUS_UNAVAILABLE_TEXT
                                }
                            };

                    }
                    else
                    {
                        return new CheckAccountResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = CheckAccountResult.STATUS_AVAILABLE_CODE,
                                statusText = CheckAccountResult.STATUS_AVAILABLE_TEXT
                            }
                        };
                    }
                }
                catch (Exception ex)
                {
                    return new CheckAccountResult
                    {
                        sysUserResultStatus =
                        {
                            statusCode = 500,
                            statusText = ex.Message
                        }
                    };
                }
            }
            else
            {
                return new CheckAccountResult
                {
                    sysUserResultStatus = request
                };
            }
        }

        public CreateAccountResult createAccountForActivating(string email, string password)
        {
            SysUserResultStatus request = requestIP();
            if (request.statusCode == 0)
            {
                try
                {
                    string _id = SysUserController.createUserForActivating(email, password);
                    if (_id != "")
                    {
                        return new CreateAccountResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = CreateAccountResult.STATUS_OK_CODE,
                                statusText = CreateAccountResult.STATUS_OK_TEXT
                            },
                            id = _id
                        };
                    }
                    else
                    {
                        return new CreateAccountResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = CreateAccountResult.STATUS_GENERAL_ERROR_CODE,
                                statusText = CreateAccountResult.STATUS_GENERAL_ERROR_TEXT
                            },
                            id = ""
                        };
                    }
                }
                catch (Exception ex)
                {
                    return new CreateAccountResult
                    {
                        sysUserResultStatus =
                        {
                            statusCode = 500,
                            statusText = ex.Message
                        },
                        id = ""
                    };
                }
            }
            else
            {
                return new CreateAccountResult
                {
                    sysUserResultStatus = request,
                    id = ""
                };
            }
        }

        public ResetActivatedTokenResult resetActivatedToken(string email)
        {
            SysUserResultStatus request = requestIP();
            if (request.statusCode == 0)
            {
                try
                {
                    string randomString = Common.getRandomString(6);
                    ResetActivatedTokenResult result = SysUserController.resetActivatedToken(email, randomString);
                    return result;
                   
                }
                catch (Exception ex)
                {
                    return new ResetActivatedTokenResult
                    {
                        sysUserResultStatus =
                        {
                            statusCode = 500,
                            statusText = ex.Message
                        },
                        token = ""
                    };
                }
            }
            else
            {
                return new ResetActivatedTokenResult
                {
                    sysUserResultStatus = request,
                    token = ""
                };
            }
        }

        public SysUserResultStatus requestIP()
        {
            OperationContext context = OperationContext.Current;
            MessageProperties messageProperties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpointProperty =
                messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            if (!checkAuthenticatedIp(endpointProperty.Address))
            {
                return new SysUserResultStatus
                {
                    statusCode = SysUserResultStatus.STATUS_UNALLOWED_IP_CODE,
                    statusText = string.Format(SysUserResultStatus.STATUS_UNALLOWED_IP_TEXT, endpointProperty.Address)
                };
            }
            else
            {
                return new SysUserResultStatus
                {
                    statusCode = SysUserResultStatus.STATUS_ALLOWED_IP_CODE,
                    statusText = SysUserResultStatus.STATUS_ALLOWED_IP_TEXT
                };
            }
        }

        private bool checkAuthenticatedIp(string iP)
        {
            string whiteIP = ConfigurationManager.AppSettings["WhiteIPs"];
            whiteIP = whiteIP.Trim();
            string[] result = whiteIP.Split(';');

            foreach (string sub in result)
            {
                string t = sub.Trim();
                if (iP == t)
                    return true;
            }
            return false;
        }


        public ResetPasswordResult resetPassword(string email)
        {
            SysUserResultStatus request = requestIP();
            if (request.statusCode == 0)
            {
                try
                {
                    ResetPasswordResult result = SysUserController.resetPassword(email);
                    return result;
                }
                catch (Exception ex)
                {
                    return new ResetPasswordResult
                    {
                        sysUserResultStatus =
                        {
                            statusCode = 500,
                            statusText = ex.Message
                        },
                        password = ""
                    };
                }
            }
            else
            {
                return new ResetPasswordResult
                {
                    sysUserResultStatus = request,
                    password = ""
                };
            }
        }
    }
}
